import { InjectRedis } from '@nestjs-modules/ioredis';
import { Injectable } from '@nestjs/common';
import { Redis } from 'ioredis';
import { RateLimiterMemory, RateLimiterRedis } from 'rate-limiter-flexible';
import { HOSTNAME } from 'src/setting';

@Injectable()
export class RateLimiterService {
  rateLimiter: RateLimiterMemory = null
  rateLimiterQuestion: RateLimiterMemory = null
  rateLimiterManager: RateLimiterRedis = null
  constructor(
    @InjectRedis() private readonly redis: Redis,
  ) {
    this.rateLimiter = new RateLimiterMemory({
      keyPrefix: 'rateLimiter',
      points: 1000,
      duration: 1
    });
    this.rateLimiterQuestion = new RateLimiterRedis({
      storeClient:this.redis,
      keyPrefix: 'rateLimiterQuestion',
      points: 100,
      duration: 1 * 60,
      dbName: !process.env.ServerApp ? "2" : process.env.redisdb
    });

    this.rateLimiterManager = new RateLimiterRedis({
      storeClient:this.redis,
      keyPrefix: 'rateLimiterManager',
      points: 20,
      duration: 60,
      dbName: !process.env.ServerApp ? "1" : process.env.redisdb
    });

  }

  async consume() {
    let key = HOSTNAME
    return new Promise((resolve, reject)=> {
      let loop = async () => {
        try {
          const res = await this.rateLimiter.consume(key);
          resolve(res)
        } catch (err) {
          setTimeout(() => {
            loop()
          }, 1000)
        }
      }
      loop()
    })
  }

  async consume_question(key, number?: number, duration?: number){
    try{
      let res = await this.rateLimiterQuestion.consume(key, number || 1, {customDuration: duration || 1 * 60 })
      console.log(res,'----res')
      if(res){
        return true
      }else{
        return false
      }
    }catch(err){
      console.log(err,'----err')

      return false
    }
  }
  
  async consume_manager(key, number?: number, duration?: number){
    try{
      let res = await this.rateLimiterManager.consume(key, number || 1, {customDuration: duration || 1 * 60 })
      console.log(res,'----res')
      if(res){
        return true
      }else{
        return false
      }
    }catch(err){
      console.log(err,'----err')

      return false
    }
  }
}
